<?php

/*
 * To change this template, choose Tools | Templates and open the template in the editor.
 */

/**
 * Description of UserController
 *
 * @author KOI
 */
class UserController extends FrontEndController {

    public function filters() {
        return array(
            'accessControl',
            'postOnly + delete'
        );
    }

    /**
     * Specifies the access control rules.
     * This method is used by the 'accessControl' filter.
     *
     * @return array access control rules
     */
    public function accessRules() {
        return array(
            array(
                'allow',
                'actions' => array(
                    'upload',
                    'like',
                    'register2',
                    'register3',
                    'register4',
                    'register5',
                    'register6',
                    'logout',
                    'follow',
                    'edit',
                    'newsfeed',
                    'newsfeedmore',
                    'createpassword',
                    'readnotify',
                    'changepassword'
                ),
                'roles' => array(
                    'member'
                )
            ),
            array(
                'allow',
                'actions' => array(
                    'view',
                    'login',
                    'fblogin',
                    'googlelogin',
                    'twlogin',
                    'register1',
                ),
                'users' => array(
                    '*'
                )
            ),
            array(
                'deny',
                'users' => array(
                    '*'
                )
            )
        );
    }

    public function actionRegister1($username = null) {
        $this->layout = 'register';
        if ($username != null && !empty($username)) {
            $inviter = User::model()->find("username=:user", array(':user' => $username));
            if ($inviter) {
                Yii::app()->session->add('inviter', $inviter->id);
            }
        }
        if (Yii::app()->user->id != null) {
            $this->redirect(Yii::app()->homeUrl);
        } else {
            $model = new User ();
            $register1 = new Register1 ();
            if (isset($_POST ['Register1'])) {
                $register1->attributes = $_POST ['Register1'];
                $register1->validate();
                if ($model->exists('email=:email', array(':email' => $register1->email))) {
                    $register1->addError('email', 'Email đã được đăng ký');
                } else {
                    $model->email = $register1->email;
                    $model->fullname = $register1->fullname;
                    $model->created_at = date("Y-m-d H:i:s");
                    $pass = $register1->password;
                    $model->password = md5($pass);
                    if ($model->save()) {
                        $login = new LoginForm('Front');
                        $login->username = $model->email;
                        $login->password = $pass;
                        if ($login->validate() && $login->login()) {
                            if (!file_exists(Yii::getPathOfAlias('webroot') . '/upload/user/' . Yii::app()->user->id)) {
                                mkdir(Yii::getPathOfAlias('webroot') . '/upload/user/' . Yii::app()->user->id, 0755);
                                mkdir(Yii::getPathOfAlias('webroot') . '/upload/user/' . Yii::app()->user->id . '/avatar', 0755);
                                mkdir(Yii::getPathOfAlias('webroot') . '/upload/user/' . Yii::app()->user->id . '/images', 0755);
                            }
                            $this->redirect('register2');
                        }
                    }
                }
            }
            $this->render('register1', array(
                'model' => $register1
            ));
        }
    }

    public function actionRegister2() {
        $this->layout = 'register';
        $model = $this->loadUser(Yii::app()->user->id);
        $register2 = new Register2 ();
        if (isset($_POST ['Register2'])) {
            $register2->attributes = $_POST ['Register2'];
            $register2->validate();
            if (!$register2->hasErrors()) {
                if ($model->exists('username=:username', array(':username' => $register2->username))) {
                    $register2->addError('username', 'Tài khoản đã được đăng ký');
                } elseif (!preg_match('/^[a-zA-Z0-9]+[_.-]{0,1}[a-zA-Z0-9]+$/m', $register2->username)) {
                    $register2->addError('username', 'Username không hợp lệ.');
                } else {
                    $uploadedFile = CUploadedFile::getInstance($register2, 'avatar');
                    $model->username = $register2->username;
                    $model->gender = $register2->gender;
                    if (!empty($uploadedFile)) {
                        $fileName = $model->username . '.' . $uploadedFile->extensionName;
                        $model->avatar = $fileName;
                    }
                    if ($model->save()) {
                        $inviter_id = Yii::app()->session->get('inviter');
                        if ($inviter_id && !empty($inviter_id)) {
                            $inviter = BonusMark::model()->find('user_id=:user', array(':user' => $inviter_id));
                            if ($inviter) {
                                $inviter->mark = $inviter->mark + 1;
                            } else {
                                $inviter = new BonusMark();
                                $inviter->id = $inviter_id;
                                $inviter->mark = 1;
                            }
                            $inviter->save();
                            Yii::app()->session->remove('inviter');
                        }

                        if (!empty($uploadedFile)) {
                            $uploadedFile->saveAs(Yii::getPathOfAlias('webroot') . '/upload/user/' . Yii::app()->user->id . '/avatar/' . $fileName);
                        }

                        $this->redirect('register3');
                    }
                }
            }
        }
        $this->render('register2', array(
            'model' => $register2
        ));
    }

    public function actionRegister3() {
        $this->layout = 'register';
        $register3 = new Register3 ();
        $register3->validate();
        if (isset($_POST ['Register3'])) {
            $register3->attributes = $_POST ['Register3'];
            Yii::app()->session->add("gender", $register3->gender);
            $this->redirect('register4');
        }
        $this->render('register3', array(
            'model' => $register3
        ));
    }

    public function actionRegister4() {
        $this->layout = 'register';
        $register4 = new Register4 ();
        if (isset($_POST ['Register4'])) {
            $register4->attributes = $_POST ['Register4'];
            $register4->validate();
            foreach ($register4->style as $s) {
                $userStyle = new UserStyle ();
                $userStyle->user_id = Yii::app()->user->id;
                $userStyle->style_id = $s;
                $userStyle->insert();
            }
            if ($userStyle->save()) {
                $this->redirect('register5');
            }
        }
        $this->render('register4', array(
            'model' => $register4
        ));
    }

    public function actionRegister5() {
        $this->layout = 'register';
        $user = $this->loadUser(Yii::app()->user->id);
        $gender = Yii::app()->session->get("gender");
        $condition = array();
        $condition [":id"] = Yii::app()->user->id;
        if ($gender == 2) {
            $genderc = "1=1";
        } else {
            $genderc = "u.gender=:gender";
            $condition [':gender'] = $gender;
        }
        $style = $user->style;
        if (!is_null($style) && sizeof($style) > 0) {
            $list = array();
            foreach ($style as $value) {
                $list [] = $value->style_id;
            }
            $lists = implode(",", $list);
            $styles = "s.style_id in ($lists)";
        } else {
            $styles = "1=1";
        }
        $sql = "Select u.id From tbl_user u left join tbl_image img on u.id = img.user_created left join tbl_user_style s on u.id = s.user_id Where u.id <>:id and " . $genderc . " and " . $styles . " GROUP BY u.id Order BY SUM(img.like_cnt) DESC LIMIT 0,20";
        $model = User::model()->findAllBySql($sql, $condition);
        if (!is_null($model) && sizeof($model) > 0) {
            $list = array();
            unset($user);
            foreach ($model as $user) {
                $list [] = $user->id;
            }
            $model = User::model()->findAll("id in (" . implode(",", $list) . ")", array());
        } else {
            $model = null;
        }
        Yii::app()->session->remove("gender");
        $checkFollow = UserFollow::model()->find("followed = :followed and follower =:follower", array(
            ':followed' => $user->id,
            'follower' => Yii::app()->user->id
        ));
        $this->render('register5', array(
            'model' => $model,
            'checkFollow' => $checkFollow
        ));
    }

    public function actionRegister6() {
        $this->layout = 'register';
        $user = $this->loadUser(Yii::app()->user->id);
        if ($user->username == null) {
            $this->render('register6');
        } else {
            $this->redirect(array('view', 'username' => $user->username));
        }
    }

    public function actionLogin() {
        $model = new LoginForm('Front');
        if (isset($_POST ['ajax']) && $_POST ['ajax'] === 'login-form') {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }

        if (isset($_POST ['LoginForm'])) {
            $model->attributes = $_POST ['LoginForm'];
            if ($model->validate() && $model->login()) {
                $this->redirect(Yii::app()->user->returnUrl);
            }
        }
        $this->render('login', array(
            'model' => $model
        ));
    }

    public function actionFbLogin() {
        Yii::import('ext.facebook.Facebook');

        $facebook = new Facebook(array(
            'appId' => '128317560709307',
            'secret' => 'feb508a994e8f14286f48b74efff5291'
        ));
        $userId = $facebook->getUser();
        if ($userId) {
            $result = $facebook->api('/me?fields=name,email');
            if (!array_key_exists('email', $result)) {
                throw new CHttpException(400, 'Đã có lỗi xảy ra trong quá trình đăng nhập bằng Facebook của bạn.');
            } else {
                $check = User::model()->find('email=:email', array(
                    ':email' => $result ['email']
                ));
                if (empty($check)) {
                    $user = new User ();
                    if (array_key_exists('email', $result)) {
                        $user->email = $result ['email'];
                    }
                    if (array_key_exists('name', $result)) {
                        $user->fullname = $result ['name'];
                    }
                    $user->password = '';
                    $user->status = User::ACCOUNT_ACTIVE;
                    $user->created_at = date('Y-m-d H:i:s');
                    $user->role = 'member';
                    $user->insert();
                    $check->attributes = $user->attributes;
                }

                $userLog = User::model()->find('email=:email', array(
                    ':email' => $result ['email']
                ));
                $model = new LoginForm('OpenId');
                $model->username = $userLog->email;
                $model->password = $userLog->password;
                if ($model->login()) {
                    if (!file_exists(Yii::getPathOfAlias('webroot') . '/upload/user/' . Yii::app()->user->id)) {
                        mkdir(Yii::getPathOfAlias('webroot') . '/upload/user/' . Yii::app()->user->id, 0755);
                        mkdir(Yii::getPathOfAlias('webroot') . '/upload/user/' . Yii::app()->user->id . '/avatar', 0755);
                        mkdir(Yii::getPathOfAlias('webroot') . '/upload/user/' . Yii::app()->user->id . '/images', 0755);

//                    $post = array(
//                        'message' => "- Mình vừa tham gia Fchic, mọi người cùng tham gia cho vui nhé :)",
//                        'name' => "Fchic.Vn - The fashion social network",
//                        'description' => "Thỏa sức thể hiện phong cách, cá tính của bạn. Kết bạn, giao lưu với các tín đồ thời trang trên khắp Việt Nam, thật hấp dẫn phải không?",
//                        'link' => 'http://fchic.vn/ver1',
////                        'picture' => "test message"
//                    );
//                    $facebook->api("/me/feed/", 'post', $post);
                    }
//                $args = array(
//                    'message' => $userLog->fullname.' đã kết nối tới Fchic.',
//                    'link'=>'http://fchic.vn/'
//                );
//                $facebook->api('/me/feed/','post', $args);

                    if (strlen($userLog->username) > 0 && strlen($userLog->gender) > 0 && strlen($userLog->avatar) > 0) {
                        $this->redirect(Yii::app()->user->returnUrl);
                    } else {
                        $this->redirect('register2');
                    }
                }
            }
        } else {
            $model = new LoginForm('Front');
            $this->render('login', array(
                'model' => $model
            ));
        }
    }

    public function actionGoogleLogin() {
        Yii::import('ext.google.contrib.Google_Oauth2Service');

        $client = new Google_Client ();
        $client->setClientId('203837015752-29f519lfk8u4fnrqmpljjmeke5rankfm.apps.googleusercontent.com');
        $client->setClientSecret('CdtV1qBYhuIT7qWT1gr-sg4w');
        $client->setDeveloperKey('AIzaSyAYxdSycRBJ6Q2HHabMDBnbiGICBkaFrE8');
        $client->setRedirectUri(Yii::app()->createAbsoluteUrl('user/googlelogin'));
        $client->setScopes("email https://www.googleapis.com/auth/userinfo.profile");
        $oauth2 = new Google_Oauth2Service($client);

        if (isset($_GET ['code'])) {
            $client->authenticate($_GET ['code']);
            $_SESSION ['token'] = $client->getAccessToken();
            $redirect = 'http://' . $_SERVER ['HTTP_HOST'] . $_SERVER ['PHP_SELF'];
        }

        if (isset($_SESSION ['token'])) {
            $client->setAccessToken($_SESSION ['token']);
        }
        if ($client->getAccessToken()) {
            $result = $oauth2->userinfo_v2_me->get();
            $_SESSION ['token'] = $client->getAccessToken();
        }
        if ($result) {
            $check = User::model()->find('email=:email', array(
                ':email' => $result ['email']
            ));

            if (empty($check)) {
                $user = new User ();
                if (array_key_exists('email', $result)) {
                    $user->email = $result ['email'];
                }
                if (array_key_exists('name', $result)) {
                    $user->fullname = $result ['name'];
                }
                $user->password = '';
                $user->status = User::ACCOUNT_ACTIVE;
                $user->created_at = date('Y-m-d H:i:s');
                $user->role = 'member';
                $user->insert();
                $check->attributes = $user->attributes;
            }
            $userLog = User::model()->find('email=:email', array(
                ':email' => $result ['email']
            ));
            $model = new LoginForm('OpenId');
            $model->username = $userLog->email;
            $model->password = $userLog->password;
            if ($model->login()) {
                if (!file_exists(Yii::getPathOfAlias('webroot') . '/upload/user/' . Yii::app()->user->id)) {
                    mkdir(Yii::getPathOfAlias('webroot') . '/upload/user/' . Yii::app()->user->id, 0755);
                    mkdir(Yii::getPathOfAlias('webroot') . '/upload/user/' . Yii::app()->user->id . '/avatar', 0755);
                    mkdir(Yii::getPathOfAlias('webroot') . '/upload/user/' . Yii::app()->user->id . '/images', 0755);
                }
                if (strlen($userLog->username) > 0 && strlen($userLog->gender) > 0 && strlen($userLog->avatar) > 0) {
                    $this->redirect(Yii::app()->user->returnUrl);
                } else {
                    $this->redirect('register2');
                }
            }
            unset($model);
            unset($result);
            unset($user);
            unset($check);
            unset($client);
            unset($oauth2);
        } else {
            $model = new LoginForm('');
            $this->render('login', array(
                'model' => $model
            ));
        }
    }

    /**
     * Logs out the current user and redirect to homepage.
     */
    public function actionLogout() {
        if (Yii::app()->user->isGuest) {
            $this->redirect(array(
                'site/index'
            ));
        }
        $user = $this->loadUser(Yii::app()->user->id);
        $user->last_visited = date('Y-m-d H:i:s');
        $user->login_type = User::OFFLINE;
        $user->update();
        $roleAssigned = Yii::app()->authManager->getRoles(Yii::app()->user->id);
        if (!empty($roleAssigned)) { // checks that there are assigned roles
            $auth = Yii::app()->authManager; // initializes the authManager
            foreach ($roleAssigned as $n => $role) {
                if ($auth->revoke($n, Yii::app()->user->id)) // remove each assigned role for this user
                    Yii::app()->authManager->save(); // again always save the result
            }
        }
        Yii::app()->user->logout();
        unset($user);
        unset($roleAssigned);
        unset($role);
        $this->redirect(Yii::app()->homeUrl);
    }

    public function actionTwLogin() {
        Yii::import('ext.twitter.TwitterOAuth');

        $oauth_token = Yii::app()->session->get("oauth_token");
        $oauth_token_secret = Yii::app()->session->get("oauth_token_secret");
        if (!empty($_GET ['oauth_verifier']) && !empty($oauth_token) && !empty($oauth_token_secret)) {
            $twitteroauth = new TwitterOAuth('c1ov9I3pAkUnRWebRug', 'Gwn4Soquts69Pj1P49YYMU99ecPpX3NoqcifKglGwA', $oauth_token, $oauth_token_secret);
            $access_token = $twitteroauth->getAccessToken($_GET ['oauth_verifier']);
            $_SESSION ['access_token'] = $access_token;
            $result = $twitteroauth->get('account/verify_credentials');

            if (!isset($result->error)) {
                $check = User::model()->find('email=:email', array(
                    ':email' => $result->screen_name . '@twitter.com'
                ));

                if (empty($check)) {
                    $user = new User ();
                    $user->email = $result->screen_name . '@twitter.com';
                    $user->fullname = $result->name;
                    $user->password = '';
                    $user->status = User::ACCOUNT_ACTIVE;
                    $user->created_at = date('Y-m-d H:i:s');
                    $user->role = 'member';
                    $user->insert();
                    $check->attributes = $user->attributes;
                }
                $userLog = User::model()->find('email=:email', array(
                    ':email' => $result->screen_name . '@twitter.com'
                ));
                $model = new LoginForm('OpenId');
                $model->username = $userLog->email;
                $model->password = $userLog->password;
                if ($model->login()) {
                    if (!file_exists(Yii::getPathOfAlias('webroot') . '/upload/user/' . Yii::app()->user->id)) {
                        mkdir(Yii::getPathOfAlias('webroot') . '/upload/user/' . Yii::app()->user->id, 0755);
                        mkdir(Yii::getPathOfAlias('webroot') . '/upload/user/' . Yii::app()->user->id . '/avatar', 0755);
                        mkdir(Yii::getPathOfAlias('webroot') . '/upload/user/' . Yii::app()->user->id . '/images', 0755);
                    }
                    if (strlen($userLog->username) > 0 && strlen($userLog->gender) > 0 && strlen($userLog->avatar) > 0) {
                        $this->redirect(Yii::app()->user->returnUrl);
                    } else {
                        $this->redirect('register2');
                    }
                }
                unset($model);
                unset($result);
                unset($user);
                unset($check);
            }
        }
        $model = new LoginForm('');
        $this->render('login', array(
            'model' => $model
        ));
    }

    public function actionCreatePassword() {
        $model = $this->loadUser(Yii::app()->user->id);
        $model->scenario = 'createPassword';
        if ($model->password == null) {
            if (isset($_POST ['User'])) {
                $model->attributes = $_POST ['User'];
                $pass = $model->newPassword;
                $model->password = md5($pass);
                if ($model->save()) {
                    $this->redirect('edit', array(
                        'model' => $model
                    ));
                }
            }
            $this->render('createPassword', array('model' => $model));
        } else {
            $this->redirect('changepassword');
        }
    }

    public function actionChangePassword() {
        $model = $this->loadUser(Yii::app()->user->id);
        $model->scenario = 'changePassword';
        if (isset($_POST ['User'])) {
            $model->attributes = $_POST ['User'];
            if (md5($model->oldPassword) != $model->password) {
                $model->addError('oldPassword', 'Mật khẩu cũ kô chính xác !');
            } else {
                $pass = $model->newPassword;
                $model->password = md5($pass);
                if ($model->save()) {
                    $this->redirect('edit', array(
                        'model' => $model
                    ));
                }
            }
        }
        $this->render('changePassword', array('model' => $model));
    }

    public function actionView($username) {
        if ($username == "" && Yii::app()->user->id != null) {
            $this->redirect('register2');
        } else {
            $model = User::model()->find('username=:username and status=:status', array(
                ':username' => $username, ':status' => 1
            ));
            if ($model) {
                $sql = 'select u.* from tbl_user u join tbl_user_follow uf where u.id=uf.follower';
                $userFollow = User::model()->findAllBySql($sql);
                $collections = Collection::model()->findAll('user_created=:user_id and status=1 order by created_at DESC', array(':user_id' => $model->id));
                $image = Image::model()->findAll('status=1 and user_created=:id order by created_at DESC limit 0,10', array(':id' => $model->id));
                $this->render('view', array(
                    'model' => $model,
                    'image' => $image,
                    'collections' => $collections,
                    'userFollow'=>$userFollow
                ));
            } else {
                throw new CHttpException(404, 'The requested page does not exist.');
            }
        }
    }

    public function actionEdit() {
        if (Yii::app()->user->isGuest) {
            $this->redirect('login');
        } else {
            $model = $this->loadUser(Yii::app()->user->id);
            $model->scenario = 'edit';
            $oldFileName = $model->avatar;
            if (isset($_POST ['User'])) {
                $model->attributes = $_POST ['User'];
                $uploadedFile = CUploadedFile::getInstance($model, 'avatar');
                if (!empty($uploadedFile)) {
                    $fileName = $model->username . $uploadedFile->extensionName;
                    $model->avatar = $fileName;
                } else {
                    $model->avatar = $oldFileName;
                }
                if ($model->save()) {
                    if (!empty($uploadedFile) && !empty($oldFileName)) {
                        unlink(Yii::getPathOfAlias('webroot') . '/upload/user/' . Yii::app()->user->id . '/avatar/' . $oldFileName);
                        $uploadedFile->saveAs(Yii::getPathOfAlias('webroot') . '/upload/user/' . Yii::app()->user->id . '/avatar/' . $fileName);
                    }
                    if (!empty($uploadedFile)) {
                        $uploadedFile->saveAs(Yii::getPathOfAlias('webroot') . '/upload/user/' . Yii::app()->user->id . '/avatar/' . $fileName);
                    }
                    $this->refresh();
                }
            }
            $this->render('edit', array(
                'model' => $model
            ));
        }
    }

    public function actionFollow($id) {
        $check = UserFollow::model()->find("followed = :followed and follower =:follower", array(
            ':followed' => $id,
            'follower' => Yii::app()->user->id
        ));
        if ($check) {
            $check->delete();
            echo 'Theo dõi';
        } else {
            $model = new UserFollow ();
            $model->followed = $id;
            $model->follower = Yii::app()->user->id;
            $model->insert();
            echo 'Bỏ theo dõi';
        }
    }

    public function actionReadNotify() {
        if (Yii::app()->user->isGuest) {
            
        } else {
            $id = Yii::app()->user->id;
            $lstFollowedID = array();
            $listImageFollow = ImageUserFollow::model()->findAll("user_id=:id", array(
                ':id' => $id
            ));
            if ((!is_null($listImageFollow)) && sizeof($listImageFollow > 0)) {

                foreach ($listImageFollow as $followed) {
                    $lstFollowedID [] = $followed->image_id;
                }
                $lstFollowed = implode(",", $lstFollowedID);
//            $sql = 'SELECT t.* FROM tbl_user_active t join tbl_image img on t.image_id = img.id where t.image_id in (' . $lstFollowed . ') and t.user_id <> :id and ((img.user_created = :id or t.active_type = :active_type )) ORDER BY active_at DESC LIMIT 0 , 10';
//            $sql = 'SELECT t.* FROM tbl_user_active t join tbl_image img on t.image_id = img.id join tbl_image_user_follow img_fl on t.user_id = img_fl.user_id join tbl_user u on u.id = t.user_id where t.active_at >img_fl.follow_at and img.status = :img_status and u.status = :user_status t.image_id in (' . $lstFollowed . ') and t.user_id <> :id and ((img.user_created = :id or t.active_type = :active_type )) ORDER BY active_at DESC LIMIT 0 , 10';
                $sql = 'SELECT t.* FROM tbl_user_active t join tbl_image img on t.image_id = img.id join tbl_image_user_follow img_fl on t.image_id = img_fl.image_id join tbl_user u on u.id = t.user_id where img_fl.user_id =:id and t.active_at >img_fl.follow_at and img.status = :img_status and u.status = :user_status and t.image_id in (' . $lstFollowed . ') and t.user_id <> :id and ((img.user_created = :id or t.active_type = :active_type )) ORDER BY active_at DESC LIMIT 0 , 1';
                $modelodel = UserActive::model()->findBySql($sql, array(
                    ':id' => $id,
                    ':active_type' => UserActive::COMMENT_IMG
                    , ':user_status' => User::ACCOUNT_ACTIVE
                    , ':img_status' => Image::IMAGE_ACTIVE
                ));
                if ($modelodel) {
                    $notifyStatus = new NotifyStatus();
                    $notifyStatus->active_id = $modelodel->id;
                    $notifyStatus->user_id = Yii::app()->user->id;
                    $notifyStatus->status = NotifyStatus::READED;
                    $notifyStatus->save();
                    echo 'ok';
                }
            }
        }
    }

    public function loadUser($id) {
        $model = User::model()->findByPk($id);
        if ($model === null)
            throw new CHttpException(404, 'The requested page does not exist.');
        return $model;
    }

}

?>
